package com.practice.dataStructure.stack;

import java.util.Arrays;

public class MyStack<E> {
    private Object[] elementData;
    private int capacity; //栈的容量
    private int count; //栈中元素的数量
    private static final int GROW_FACTOR = 2;

    public MyStack(){
        this.capacity = 8;
        this.elementData = new Object[8];
        this.count = 0;
    }

    public MyStack(int initialCapacity){
        if(initialCapacity<1){
            throw  new IllegalArgumentException("InitialCapacity is too small");
        }
        this.capacity = initialCapacity;
        this.elementData = new Object[initialCapacity];
        this.count = 0;
    }

    //入栈
    public void push(E value){
        if(count == capacity){
            ensureCapacity();
        }
        elementData[count++] = value;
    }

    //确保容量大小
    private void ensureCapacity(){
        int newCapacity = capacity * GROW_FACTOR;
        elementData = Arrays.copyOf(elementData,newCapacity);
        capacity = newCapacity;
    }

    //返回栈顶元素并出栈
    public E pop(){
        if(isEmpty()){
            throw new IllegalArgumentException("The Stack is empty");
        }
        count--;
        return (E) elementData[count];
    }

    //返回栈顶元素不出栈
    public E peek(){
        if(isEmpty()){
            throw new IllegalArgumentException("The Stack is empty");
        }
        return (E) elementData[count-1];
    }

    public boolean isEmpty(){
        return count==0;
    }

    public int size(){
        return count;
    }
}
